import Vue from 'vue';
import VueResource from 'vue-resource';
import store from '../store';
import {Toast} from 'mand-mobile'
Vue.use(VueResource);

const appid = 'wxe6ab26eb9276d633';
const secret = '0d1750587901b3570a84b6b0ca4e8dff';

let accessToken = store.state.accessToken;

const API_ROOT = '/';

async function fetch(service, data, loading = false)
{
  let accessToken = store.state.accessToken;
  const user = store.state.user

  if(!accessToken)
  {
    // accessToken = await getData('AccessToken.GetAccessToken',{appid, secret});
    // store.dispatch('saveAccssToken', accessToken)
  }
  return getData(service, data, loading)

}
async function getData(service, datas, loading)
{
  const data = {
    service,
    access_token: store.state.accessToken,
    ...datas
  }
  if(loading)
  {
    Toast.loading('加载中...')
  }

  return new Promise((resolve, reject)=>{
    Vue.http.options.emulateJSON = true;
    Vue.http.post(API_ROOT + 'index.php', data).then(response => {
      Toast.hide();
      if (response.status == 200) {
        let data = response.data
        // console.log(data);
        if(data.ret == 200)
        {
          resolve(data.data);
          return;
        }else if (data.ret == 401 || data.ret == 400){
            Toast.failed(data.msg)
        }else if (data.ret == 402) {
          const accessToken = store.state.accessToken
          const user = store.state.user;
          /*if (user && accessToken) {
            return fetch('AccessToken.UpdateAccessToken', { appid, secret }).then(res => {
              return fetch(service, datas)
            })
          }else if (!accessToken) {*/
            return fetch('AccessToken.GetAccessToken', { appid, secret }).then(res => {
              store.dispatch('saveAccssToken', response.data.data.result)
              return fetch(service, datas)
            })
          //}
        }else {
            Toast.failed(data.msg)
        }
      }

      reject(data)

    },error => {
        Toast.failed(JSON.stringify(error))
    })
  })
}
//暴露外围函数
export function test() {
    return fetch('App.News.Index');
}
export function News(data) {
    return fetch('App.News.Index',data);
}
export function RedirectWeixin(data)
{
  let user = store.state.user;
  if(!user.id)
  {
    var ret = fetch('Weixin.Redirect_weixin',data,true);
    ret.then(res => {
      window.location.href=res;
    })
  }
}
